package com.dqlp.yf.rabbitmq.sender;

import com.dqlp.yf.rabbitmq.constant.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * @program: rabbitmq
 * @description:    延迟队列
 * @author: andy
 * @create: 2019-09-09 14:08
 */
@Component
@Slf4j
public class LazySender implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    final
    RabbitTemplate rabbitTemplate;

    @Autowired
    public LazySender(RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setReturnCallback(this::returnedMessage);
        rabbitTemplate.setConfirmCallback(this::confirm);
        this.rabbitTemplate = rabbitTemplate;
    }

    public void lazySender(String msg,String routingKey) {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDelay(MqConstant.delay);  //设置延迟的时间
        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
        Message message = new Message(msg.getBytes(),messageProperties);
        rabbitTemplate.convertAndSend(MqConstant.LAZY_EXCHANGE,routingKey,message);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, @Nullable String cause) {
        System.out.println(correlationData);
        if (ack) {
            log.info("延迟队列接收成功");
        } else {
            log.info("延迟队列出现异常");
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.info("message:{},replyCode:{},replyText:{},exchange:{},routingkey:{}",message,replyCode,replyText,exchange,routingKey);
    }
}
